#!/usr/bin/perl -wc

package RFCMail::ESMTP::Server::Salvage::Greeting;

use strict;
use RFCMail::ESMTP::Grammar::Base qw(DOMAIN_ARG_RE);


sub init {
    my $self = shift;
    $self->SUPER::init(@_);
    if (not exists($self->{salvage_greeting}) or $self->{salvage_greeting}) {
	my $any_re = qr'\A(.*)\z';
	$self->{handlers}->set('EHLO', $any_re, 'ehlo_salvager');
	$self->{handlers}->set('HELO', $any_re, 'ehlo_salvager');
    }
}


sub ehlo_salvager {
    my ($self, $cmd, $arg) = @_;
    if ($arg =~ DOMAIN_ARG_RE) {
	delete($self->{state}->{Invalid_Greeting});
	return ($self->ehlo_handler($cmd, $arg));
    }
    else {
	$self->{state}->{Invalid_Greeting} = $arg;
	# The above change of state is not impacted by ehlo_handler() calling reset()
	my $domain = $self->peer_address_literal('[127.0.0.1]');
	$self->logmsg(i => "'$cmd $arg' is invalid; substituting '$cmd $domain'");
	return ($self->ehlo_handler($cmd, $domain));
    }
}


1;
